package it.storm.solution;

/**
 * 48. 旋转图像
 * https://leetcode-cn.com/problems/rotate-image/submissions/
 */
public class Solutions_48 {
    public static void main(String[] args) {
//        int[][] matrix = {{1, 2, 3},
//                          {4, 5, 6},
//                          {7, 8, 9}};  // change:{{7, 4, 1},
//                                                  {8, 5, 2},
//                                                  {9, 6, 3}};

        int[][] matrix = {{5, 1, 9, 11},
                          {2, 4, 8, 10},
                          {13, 3, 6, 7},
                          {15, 14, 12, 16}};  // change: {{15, 13, 2, 5},
//                                                        {14, 3, 4, 1},
//                                                        {12, 6, 8, 9},
//                                                        {16, 7, 10, 11}}

        rotate(matrix);
        System.out.println(matrix);
    }

    public static void rotate(int[][] matrix) {
        if (matrix == null) {
            return;
        }
        int n = matrix.length;
        if (n < 2) {
            return;
        }

        // 1.左上-右下对角线元素翻转
        for (int i = 1; i < n; i++) {
            for (int j = 0; j < i; j++) {
                // 第 i 行交换前 i 个，[2,0] 与 [0,2] 交换，[2,1] 与 [1,2] 交换
                int temp = matrix[i][j];
                matrix[i][j] = matrix[j][i];
                matrix[j][i] = temp;
            }
        }
        // 2.每一行进行左右翻转
        int mid = n / 2;
        for (int i = 0; i < n; i++) {
            for (int j = 0; j < mid; j++) {
                int temp = matrix[i][j];
                matrix[i][j] = matrix[i][n - 1 - j];
                matrix[i][n - 1 - j] = temp;
            }
        }
    }
}
